<template>
  <div>
    <!-- 搜索和功能按钮区域 -->
    <div style="padding: 5px 0">
      <el-input v-model="searchText" @keyup.enter.native="load" placeholder="搜索食品" style="width: 200px">
        <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button @click="serach" round type="primary" style="margin: 5px">搜索</el-button>
      <el-button @click="reset" round type="info" style="margin: 5px">重置</el-button>
      <el-button @click="showAddDialog" round type="success" style="margin: 5px">新增食品</el-button>
    </div>

    <!-- 食品数据表格 -->
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="食品ID" width="80px"></el-table-column>

      <el-table-column prop="dishesName" label="食品名称"></el-table-column>

      <el-table-column label="食品图片" width="120px">
        <template slot-scope="scope">
          <img :src="getImgUrl(scope.row.imgUrl)" style="width: 90px; height: 80px;">
        </template>
      </el-table-column>

      <el-table-column prop="description" label="食品描述"></el-table-column>

      <el-table-column prop="price" label="价格"></el-table-column>

      <el-table-column prop="categoryId" label="分类"></el-table-column>

      <el-table-column prop="recommend" label="推荐"></el-table-column>

      <el-table-column fixed="right" label="操作" width="200px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="edit(scope.row)"></el-button>
          <el-popconfirm @confirm="del(scope.row.id)" title="确定删除该食品吗？">
            <el-button type="danger" icon="el-icon-delete" circle slot="reference"
              style="margin-left: 10px;"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin-top: 10px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-size="pageSize" :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </div>

    <!-- 新增食品弹窗 -->
    <el-dialog title="新增食品" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form :model="entity">
        <el-form-item label="食品名称" label-width="120px">
          <el-input v-model="entity.dishesName" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="食品描述" label-width="120px">
          <el-input v-model="entity.description" autocomplete="off" type="textarea" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="价格" label-width="120px">
          <el-input v-model="entity.price" type="number" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="分类ID" label-width="120px">
          <el-input v-model="entity.categoryId" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="推荐" label-width="120px">
          <el-input v-model="entity.recommend" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="食品图片" label-width="120px">
          <el-upload :accept="acceptAstrict" class="avatar-uploader" action="#" :http-request="uploadFiles"
            :show-file-list="false">
            <div class="iconBox">
              <i title="点击上传图片" v-if="!imgUrl" class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
          <el-image v-if="imgUrl" :src="imgUrl" :preview-src-list="[imgUrl]"></el-image>
          <div title="点击删除图片" v-if="imgUrl" class="gbtpBox" @click="imageRemove"><span>×</span></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改食品弹窗 -->
    <el-dialog title="修改食品" :visible.sync="dialogFormVisible2" width="40%" :close-on-click-modal="false">
      <el-form :model="entity">
        <el-form-item label="食品名称" label-width="120px">
          <el-input v-model="entity.dishesName" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="食品描述" label-width="120px">
          <el-input v-model="entity.description" autocomplete="off" type="textarea" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="价格" label-width="120px">
          <el-input v-model="entity.price" type="number" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="分类ID" label-width="120px">
          <el-input v-model="entity.categoryId" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="推荐" label-width="120px">
          <el-input v-model="entity.recommend" autocomplete="off" style="width: 100%;"></el-input>
        </el-form-item>

        <el-form-item label="食品图片" label-width="120px">
          <el-upload :accept="acceptAstrict" class="avatar-uploader" action="#" :http-request="uploadFiles"
            :show-file-list="false">
            <div class="iconBox">
              <i title="点击上传图片" v-if="!imgUrl" class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
          <el-image v-if="imgUrl" :src="imgUrl" :preview-src-list="[imgUrl]"></el-image>
          <div title="点击删除图片" v-if="imgUrl" class="gbtpBox" @click="imageRemove"><span>×</span></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="save2">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'Foods',
  data () {
    return {
      fileList: [],
      searchText: '',
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      uploadUrl: '上传接口',
      entity: {
        dishesName: '',
        description: '',
        price: '',
        categoryId: '',
        recommend: '',
        imgUrl: '' // 保存文件名
      },
      total: 0,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      acceptAstrict: '.jpg,.jpeg,.png,.JPG,.PNG', // 文件上传限制
      imgUrl: '' // 图片地址
    }
  },
  created () {
    this.load()
  },
  methods: {
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange (pageNum) {
      this.pageNum = pageNum
      this.load()
    },

    async load () {
      const res = await this.$http.get('/dishes/current/' + this.pageNum + '/size/' + this.pageSize)
      // eslint-disable-next-line eqeqeq
      if (res.code == 200) {
        this.tableData = res.data.list
        this.total = res.data.total
      }
    },
    async serach () {
      const res = await this.$http.post('/dishes/current/' + this.pageNum + '/size/' + this.pageSize, {
        dishesName: this.searchText
      })
      if (res.code === 200) {
        this.tableData = res.data.list
        this.total = res.data.total
      } else {
        this.$message.error('查询失败')
      }
    },
    reset () {
      this.searchText = '';
      this.load()
    },
    showAddDialog () {
      this.entity = {}
      // 清除之前的图片预览
      this.imgUrl = ''
      this.dialogFormVisible = true
    },
    async edit (food) {
      this.entity = JSON.parse(JSON.stringify(food))
      // 设置图片预览URL
      if (food.imgUrl) {
        // 如果是HTTP/HTTPS URL或相对路径，直接使用
        if (food.imgUrl.startsWith('http://') || food.imgUrl.startsWith('https://') || food.imgUrl.startsWith('/')) {
          this.imgUrl = this.getImgUrl(food.imgUrl)
        } else if (food.imgUrl.startsWith('file:///')) {
          // 如果是file:///格式，尝试提取文件名并加载本地资源
          try {
            const fileName = food.imgUrl.split('/').pop()
            this.imgUrl = require('@/assets/img/' + fileName)
          } catch (e) {
            this.imgUrl = ''
          }
        } else {
          // 其他情况，尝试作为相对路径处理
          this.imgUrl = this.getImgUrl(food.imgUrl)
        }
      } else {
        this.imgUrl = ''
      }
      this.dialogFormVisible2 = true
    },
    uploadFiles (file) {
      // 调用文件大小校验方法
      if (this.beforeUpload(file.file)) {
        try {
          // 创建本地URL用于预览
          const localUrl = URL.createObjectURL(file.file)
          // 本地预览使用本地URL
          this.imgUrl = localUrl
          // 创建FormData对象用于上传文件
          const formData = new FormData()
          formData.append('file', file.file)
          // 调用后端上传接口
          this.$http.post('/dish/image', formData).then(res => {
            if (res.code === 200) {
              // 更新图片URL为后端返回的URL
              this.entity.imgUrl = res.data
              this.$message.success('图片上传成功')
            } else {
              this.$message.error('图片上传失败：' + res.msg)
            }
          }).catch(error => {
            this.$message.error('图片上传失败，请稍后重试')
          })
        } catch (error) {
          this.$message.error('图片处理失败，请稍后重试')
        }
      }
    },
    // 删除图片
    imageRemove () {
      // 清除预览图片
      this.imgUrl = ''
      // 清除实体中的图片URL
      this.entity.imgUrl = ''
      this.$message({
        message: '删除图片成功',
        type: 'success'
      })
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJpgOrPng) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJpgOrPng && isLt2M
    },

    async save () {
      const res = await this.$http.post('/dish', this.entity)
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.dialogFormVisible = false
        this.load()
      } else {
        this.$message({
          type: 'error',
          message: '失败'
        })
      }
    },
    async save2 () {
      const res = await this.$http.put('/dish/' + this.entity.id, this.entity)
      if (res.code === 200) {
        this.$message.success('修改成功')
        this.dialogFormVisible2 = false
        this.load()
      } else {
        this.$message.error('修改失败')
      }
    },
    async del (id) {
      const res = await this.$http.delete('/dish/' + id)
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.load()
      } else {
        this.$message({
          type: 'error',
          message: '删除失败'
        })
      }
    },
    // 处理图片URL的方法
    getImgUrl (url) {
      if (!url) return require('@/assets/img/food.jpg')

      // 处理file:///格式的URL
      if (url.startsWith('file:///')) {
        // 从URL中提取文件名
        const fileName = url.split('/').pop()
        // 使用require加载本地资源
        try {
          return require('@/assets/img/' + fileName)
        } catch (e) {
          return require('@/assets/img/food.jpg')
        }
      } else if (url.startsWith('http://') || url.startsWith('https://')) {
        // 如果是HTTP/HTTPS URL，直接返回
        return url
      } else {
        // 其他情况，尝试作为相对路径处理
        // 如果URL是后端返回的相对路径，拼接基础URL
        if (url.startsWith('/')) {
          const baseUrl = 'http://localhost:8080' // 与axios.defaults.baseURL保持一致
          return baseUrl + url
        }
        // 否则尝试作为本地资源加载
        try {
          return require('@/assets/img/' + url)
        } catch (e) {
          return require('@/assets/img/food.jpg')
        }
      }
    }
  }
}

</script>
